package ltd.hyangyang.rpc.common.utils;

import io.netty.util.internal.StringUtil;
import ltd.hyangyang.rpc.common.bean.RpcProperties;
import ltd.hyangyang.rpc.common.constant.RegistryEnum;
import ltd.hyangyang.rpc.common.exception.ExceptionEnum;
import ltd.hyangyang.rpc.common.exception.RpcException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

public class PropertiesReadUtils {


    public static Properties propertiesRead(String fileName) throws IOException {
        if (StringUtils.isEmpty(fileName)){
            throw new RpcException(ExceptionEnum.NOT_FIND_FILE.getMsg());
        }
        Resource resource = new ClassPathResource(fileName);
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        return properties;
    }

    public static String getValue(String fileName,String key) throws IOException {
        Properties properties = propertiesRead(fileName);
        String value = properties.getProperty(key);
        return value;
    }



    public static RpcProperties initProperties() throws IOException {

        //获得实例
        RpcProperties rpcProperties = SingletonFactory.getSingletonBean(RpcProperties.class);
        if (StringUtils.isEmpty(rpcProperties.getRegistryType())){
            String registryTypeKey = getValue(rpcProperties.getFileName(), rpcProperties.getRegistryTypeKey());
            rpcProperties.setRegistryType(registryTypeKey);
        }
        if (StringUtils.isEmpty(rpcProperties.getAddr())){
            String addr = getValue(rpcProperties.getFileName(), rpcProperties.getRegistryAddrKey());
            rpcProperties.setAddr(addr);
        }

        return rpcProperties;
    }
}
